<template>
  <div class="permission">
    <el-card>
      <div style="text-align:right">
        <el-button type="primary" size="small" @click="addClick('0', 1)"
          >添加菜单（一定是添加页面）</el-button
        >
      </div>
      <el-table :data="list" row-key="id">
        <!-- 树形table渲染
        1：数据要是树形数据结构 （要有children子集）
          a:找出数据的第一层(先找出第一层pid对应的所有项)          
            
          b:再处理它的children
        2：el-table  row-key:当前条数据的唯一标识的字段名 
         -->
        <el-table-column label="菜单名称" prop="name"></el-table-column>
        <el-table-column label="权限标识" prop="code"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <!-- 页面下面可以添加页面与按钮，按钮下面不能做任何添加 -->
            <el-button
              type="text"
              v-if="row.type === 1"
              @click="addClick(row.id, 1)"
              >添加页面</el-button
            >
            <el-button
              type="text"
              v-if="row.type === 1"
              @click="addClick(row.id, 2)"
              >添加按钮</el-button
            >
            <el-button type="text" @click="del(row.id)">删除</el-button>
            <el-button type="text" @click="edit(row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增弹框组件 -->
    <Add ref="add" @getData="getData"></Add>
  </div>
</template>
<script>
import { sysPermission, sysPermissionDelete } from '@/api/permission'
import Add from './components/Add.vue'
export default {
  components: {
    Add
  },
  data () {
    return {
      list: []
    }
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await sysPermission()
      this.list = this.changeData(res.data)
      console.log('权限列表数据', res)
    },
    // 树形数据转换
    changeData (arr, str = '0') {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    // 新增点击
    addClick (pid, type) {
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'add'
      this.$refs.add.form.type = type
      this.$refs.add.form.pid = pid
    },
    // 编辑按钮点击
    edit (row) {
      // 打开弹框
      this.$refs.add.isShow = true
      // 调整mode的值
      this.$refs.add.mode = 'edit'
      // 深拷贝赋值当前行数据
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    },
    // 删除点击事件
    del (id) {
      this.$confirm('您确定删除该项吗?', '提示')
        .then(async () => {
          // 调用删除api
          await sysPermissionDelete(id)
          this.$message.success('删除成功')
          // 刷新列表数据
          this.getData()
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="scss" scoped>
.permission {
  padding: 15px;
}
</style>
